<template>
	<view class="contain">
		<block v-if="showPage">
		<block v-if="showAddress">
		<view class="pay-address" v-if="addressList.length>0" @click="gotoAddress()">
			<view class="address-userinfo">
			    <image class="address-userinfo--icon" src="../../static/shop/pay/address.png"/>
			    <view class="address-userinfo--name">{{ address.connector }}</view>
			    <view class="address-userinfo--tel">{{ address.phone }}</view>
			</view>
			<view class="address-detail">
			     <view>{{ address.province }}/{{ address.city }}/{{ address.region }}<br />{{ address.address }} </view>
			     <view><van-icon name="arrow" size="5vw" /></view>
			</view>
		</view>
		<view class="pay-address" v-else @click="gotoAddress()">
			 <view class="address-userinfo"></view>
			 <view class="address-detail">
			    <view>暂无地址，请添加</view>
			    <view><van-icon name="arrow" size="5vw" /></view>
			 </view>
		</view>
		</block>
		<view class="pay-shopping">
		    <view class="shopping-title">
		          <image class="address-userinfo--icon" src="../../static/shop/pay/shop.png"/>
		          共{{ orderList.length }}件商品
		    </view>
		    <view class="shopping-shop" v-for="(item, index) in orderList" :key="index">
		          <view class="shopping-shop--img">
		            <van-image
		              width="100"
		              height="100"
		              lazy-load
		              :src="item.model.img"
		              fit="cover"
		            />
		          </view>
		          <view class="shopping-shop--text">
		             <view>{{ item.name }}</view>
		             <view>{{ item.model.specificationsValue.replace(/"|{|}/g, "") }}</view>
		             <view><view>￥{{ item.model.price }}</view><view>x{{ item.count }}</view></view>
		          </view>
		    </view>
		    <view class="discount-cost" v-if="discount != 0">
		          <view>优惠</view>
		          <view>-￥{{ discount.toFixed(2) }}</view>
		    </view>
		</view>
		<view class="pay-othermsg">
		       <van-cell-group inset>
				<van-cell @click="handleCoupon" :value="couponText" value-class="value-class" center size="large" is-link>
				  <view slot="title">
					<view class="cell-left">
						<view class="van-cell-title">优惠劵</view>
						<view class="van-cell-text">{{coupon}}</view>
				    </view>
				  </view>
				</van-cell>
		        <van-cell :value="freight? `+ ￥${freight}` : '免邮'" :value-class=" freight? 'redColor' : 'value-class' "  center size="large" is-link>
		          <view slot="title">
					<view class="cell-left">
						<view class="van-cell-title">配送方式</view>
						<view class="van-cell-text">{{distribution}}</view>
				    </view>
		          </view>
		        </van-cell>
		        <van-cell @click="showPayType=true" value="选择" value-class="value-class" center size="large" is-link>
		          <view slot="title">
		        	<view class="cell-left">
		        		<view class="van-cell-title">支付方式</view>
		        		<view class="van-cell-text">{{payType}}</view>
		            </view>
		          </view>
		        </van-cell>
		       </van-cell-group>
		        <van-field
		          :value="leavingMsg"
		          rows="2"
				  @change="fieldChange"
		          autosize
		          label="买家留言"
		          type="textarea"
		          maxlength="50"
		          placeholder="请输入留言"
		          show-word-limit
		        />
	    </view>
		<van-submit-bar
		  :price="totalPirce"
		  button-type="danger"
		  button-text="提交订单"
		  @submit="onSubmit"
		/>
		<!-- 选择支付方式弹窗 -->
		<u-picker @confirm="choosePayType" title="支付方式" safe-area-inset-bottom v-model="showPayType" mode="selector" :range="columns" :default-selector="[0]"></u-picker>
	    <!-- 优惠券弹框 -->
		<van-popup get-container="body" :show="showCoupon" custom-style="min-height:90vh;" round  z-index="300" position="bottom"  @close="showCoupon=false">
	    	<view style="background-color:rgb(245,247,249);height:88vh;width: 100vw;">
			<view style="height:74vh;overflow-y: scroll;" >
			<van-tabs  id="tabs"  :active="active" @change="onChange">
	    	  <van-tab :title="canUse">
				  <view v-if="availableCouponList.length==0" class="contain-empty"><u-empty  mode="coupon"></u-empty></view>
				  <block v-else >
				        <div @click="chooseCouponed(index)" class="coupon-item" v-for="(item, index) in availableCouponList" :key="index">
							<view class="checkedbox"><van-checkbox checked-color="red" :value="item.checked"></van-checkbox></view>
				            <div class="shop-coupon">
				              <div class="shop-coupon--left" style="color: red;">
				                <div style="margin-bottom: 20rpx;"><text style="font-size: 30px;margin-right: 5rpx;">{{ item.discount }}</text><span>元</span></div>
				                <div v-if="Number(item.threshold)">
				                  满{{ item.threshold }}可用
				                </div>
				                <div v-else>无使用门槛</div>
								<div style="margin-top: 4rpx;">优惠{{ item.discount }}元</div>
				              </div>
				              <div class="shop-coupon--right">
				                <div style="margin-bottom: 30rpx; font-size: 28rpx;">{{ item.name }}</div>
				                  <div>开始时间：{{ item.collectionTime }}</div>
				                  <div>结束时间：{{ item.usefulEndTime }}</div>
				              </div>
				            </div>
							<van-divider
							  :style="{
							    color: '#1989fa',
							    borderColor: '#fff',
							    padding: '0 0px',
							  }"
							>
							</van-divider>
				            <div class="van-ellipsis">
				              {{ item.wares ? "可用商品：" + item.wares.name : "通用优惠券" }}
				              <span
				                v-if="item.isOver === 1"
				                style="margin-left: 2vw; font-weight: bold"
				                >已失效</span
				              >
				            </div>
				         
				        </div>
				    </block>
			  </van-tab>
	    	  <van-tab :title="noUse">
				 <view v-if="unAvailableCouponList.length==0" class="contain-empty"><u-empty  mode="coupon"></u-empty></view>
			     <block v-else >
			           <div class="coupon-item" v-for="(item, index) in unAvailableCouponList" :key="index">
			               <div class="shop-coupon">
			                 <div class="shop-coupon--left">
			                   <div style="margin-bottom: 20rpx;"><text style="font-size: 30px;margin-right: 5rpx;">{{ item.discount }}</text> <span>元</span></div>
			                   <div v-if="Number(item.threshold)">
			                     满{{ item.threshold }}可用
			                   </div>
			                   <div v-else>无使用门槛</div>
							   <div style="margin-top: 4rpx;">优惠{{ item.discount }}元</div>
			                 </div>
			                 <div class="shop-coupon--right">
			                   <div style="margin-bottom: 30rpx; font-size: 28rpx;">{{ item.name }}</div>
			                     <div>开始时间：{{ item.collectionTime }}</div>
			                     <div>结束时间：{{ item.usefulEndTime }}</div>
			                 </div>
			               </div>
						   <van-divider
						     :style="{
						       color: '#1989fa',
						       borderColor: '#fff',
						       padding: '0 0px',
						     }"
						   >
						   </van-divider>
			               <div  class="van-ellipsis">
			                 {{ handleCondition(item.wares.id)? `仅限商品：${item.wares.name}`  : "未达到满减门槛或金额不符合使用条件" }}
			                 <span
			                   v-if="item.isOver === 1"
			                   style="margin-left: 2vw; font-weight: bold"
			                   >已失效</span
			                 >
			               </div>
			            
			           </div>
			       </block>
			  </van-tab>
	    	</van-tabs>
	    	</view>
	        <view class="btn-fiexd-coupon">
				<view class="btn-div-v" @click="handleCancleCoupon" style="background-color: #ee0a24;">不使用优惠券</view>
				<view class="btn-div-v" @click="addCoupon" style="background-color: #3b89ed;">添加优惠券</view>
			</view>
			</view>
	    </van-popup>
	</block>
	</view>
</template>

<script>
	import api from '../../untils/api.js'
	export default {
		data() {
			return {
				freight:0,
				active:0,
				canUse:"",
				noUse:"",
				availableCouponList:[],
				unAvailableCouponList:[],
				showCoupon:false,
				addressList:[],
				address:{},
				orderList:[],
				orderFrom:0,
				discount:0,
				payType:"微信支付",
				distribution:"普通配送",
				coupon:"",
				columns: ["微信支付", "线下支付"],
				leavingMsg:"",
				showPayType:false,
				totalPirce:0,
				originalPrice:0,
				couponText:"",
				couponId:0,
				couponWaresId:0,
				showDefault:true,
				showPage:false,
				showAddress:false,
				shareUserId:0,
			}
		},
		methods: {
			handleCondition(id){
				var flag=true
				this.orderList.forEach((item)=>{
					if(item.orderId&&item.orderId==id){
						flag=false
					}
					if(item.wares&&item.wares.id==id){
						flag=false
					}
				})
				return flag
			},
			fieldChange(e){
				this.leavingMsg=e.detail;
			},
			handleCancleCoupon(){
				this.availableCouponList.forEach((item)=>{
					item.checked=false
				});
				this.discount=0;
				if(this.availableCouponList.length==0){
					this.couponText="暂无可用"
				}
				else {
					this.couponText=`${this.availableCouponList.length}张可用`
				}
				this.showCoupon=false;
				this.couponId=0;
				this.couponWaresId=0;
	            this.totalPirce=this.originalPrice;
			},
			chooseCouponed(i){
		        for(var z=0;z<this.availableCouponList.length;z++){
					if(z==i){
						this.$set(this.availableCouponList[z], 'checked', true)
					}
					else {
						this.$set(this.availableCouponList[z], 'checked', false)
					}
				};
				setTimeout(()=>{this.showCoupon=false},500);
				this.discount=this.availableCouponList[i].discount
				this.couponText=`-￥${this.discount.toFixed(2)}`
				this.totalPirce=this.originalPrice-this.discount*100
				this.couponId=this.availableCouponList[i].id;
				if(this.availableCouponList[i].wares&&this.availableCouponList[i].wares.id){
					this.couponWaresId=this.availableCouponList[i].wares.id
				}
			},
			addCoupon() {
			      const _that = this;
			      wx.scanCode({
			        success: async (res) => {
					let obj={couponNum:res.result};
			       const body=  await  api.SM_USER_COUPON_BIND( JSON.stringify(obj))
			       if(body.data.header.result_code==0){
								_that.getCouponData();
								uni.showToast({
								  title: '优惠券绑定成功！',
								  icon:"none",
								  duration: 2000
								}) 
							   }  
			        },
			      });
			  },
			onChange(i){
				console.log(i)
			},
			handleCoupon(){
				this.showCoupon=true;
				setTimeout(()=>{this.selectComponent('#tabs').resize();},300)
			},
		  async	onSubmit(){
				if(this.addressList.length==0){
					uni.showToast({
						title: "地址不能为空！",
						icon:'none',
						duration:1000
					});
				}
				else {
					console.log(this.leavingMsg);
					console.log(this.orderList);
					var parObj={};
					parObj.leavingMsg=this.leavingMsg
					parObj.orderFrom=this.orderFrom
					parObj.shareUserId=this.shareUserId
					parObj.modelInfo=[]
					parObj.smShippingAddress={id:this.address.id}
					if(this.couponId){
						parObj.useCoupon=true
						var flag=0;
						if(this.couponWaresId){
							this.orderList.forEach((item)=>{
								if(this.couponWaresId == (item.orderId||item.wares.id)){
									flag++
								}
							})
						}
						if(this.couponWaresId==0||flag!=1){
							parObj.coupon={ id: this.couponId }
						};
					}
					else {
						parObj.useCoupon=false
					}
					parObj.orderList=[]
					var flag=0;
					if(this.couponWaresId){
						this.orderList.forEach((item)=>{
							if(this.couponWaresId == (item.orderId||item.wares.id)){
								flag++
							}
						})
					}
					this.orderList.forEach((item)=>{
						console.log(item)
						var obj={}
						var modelObj={}
						modelObj.count=item.count;
						modelObj.id=item.model.id;
						obj.count=item.count;
						obj.waresModelID=item.model.id;
						obj.waresID=item.orderId||item.wares.id;
						obj.shoppingCartID=item.id||"";
						if(flag==1&&this.couponId&&this.couponWaresId&&this.couponWaresId==(item.orderId||item.wares.id)&&this.discount<item.model.price){
							obj.usingCouponsID=this.couponId;
						}
						parObj.orderList.push(obj)
						parObj.modelInfo.push(modelObj)
					})
				   await api.SM_ORDER_SAVE(JSON.stringify(parObj)).then((res)=>{
					   this.orderId=res.data.body.id
				     });
					 if(this.payType=="微信支付"){
						var that=this;
						var obj={};
						obj.id=this.orderId;
						obj.clientType=2;
						obj.modelInfo=[];
						var modelObj={};
						this.orderList.forEach((item)=>{
											 modelObj.id=item.model.id
											 modelObj.count=item.count
											 obj.modelInfo.push(modelObj)
						});
						api.WX_CREATE_SM_PAY(JSON.stringify(obj)).then((res)=>{
											   wx.requestPayment({
											     timeStamp: res.data.body.timeStamp,
											     nonceStr: res.data.body.nonceStr,
											     package: res.data.body.packageValue,
											     signType: 'MD5',
											     paySign: res.data.body.paySign,
											     success:  async (res)=>{
													 wx.showToast({
													   title: '后台订单处理中',
													   icon: 'loading',
													   duration: 3000
													 })
													await setTimeout(()=>{
														 uni.redirectTo({
														   url: `../orderDetail/orderDetail?id=${that.orderId}`
														 })
													 },3000)
												 },
											     fail: async (res)=> { 
													 console.log("dagfsdg")
													 await api.SM_PAY_CANCEL(JSON.stringify(that.orderId));
													 uni.redirectTo({
													   url: `../orderDetail/orderDetail?id=${that.orderId}`
													 })
													},
											   })
						}) 
					 }
					 else {
						 api.SM_ORDER_PAYMENT(JSON.stringify({id:this.orderId,payment:0})).then((res)=>{
							 if(res.data.header.result_code==0){
								uni.redirectTo({
								  url: `../orderDetail/orderDetail?id=${this.orderId}`
								})  
							 }
						 })
					 }
				}
			},
		  async	getCouponData(){
				var parObj={};
				parObj.leavingMsg=this.message
				parObj.orderFrom=this.orderFrom
				parObj.shareUserId=this.shareUserId
				// parObj.useCoupon=false
				parObj.orderList=[]
				this.orderList.forEach((item)=>{
					var obj={}
					obj.count=item.count;
					obj.waresModelID=item.model.id;
					obj.waresID=item.orderId||item.wares.id
					if(this.orderFrom==1){
						obj.shoppingCartID=item.id
					}
					parObj.orderList.push(obj)
				})
			  await	api.SM_USER_COUPON_LIST_FOR_ORDER(JSON.stringify(parObj)).then((res)=>{
					res.data.body.availableCouponList.forEach((item)=>{
		                   item.checked=false;
					});
					this.availableCouponList=res.data.body.availableCouponList;
					this.unAvailableCouponList=res.data.body.unAvailableCouponList;
					this.canUse=`可用(${res.data.body.availableCouponList.length})`
					this.noUse=`不可用(${res.data.body.unAvailableCouponList.length})`
					if(res.data.body.availableCouponList.length==0){
						this.couponText="暂无可用"
					}
					else {
						this.couponText=`${res.data.body.availableCouponList.length}张可用`
					}
				})
			},
			choosePayType(e){
				this.payType=this.columns[e[0]]
			},
			gotoAddress(){
				uni.navigateTo({
					url:"../address/address?isChoose=true",
				})
				this.showDefault=true
			},
		  async	init(){
			   this.showPage=false;
			  uni.showLoading({
			  	title:"加载中"
			  });
				if(this.orderFrom==2){
					this.orderList.forEach((item)=>{
						this.freight=this.freight+item.model.freight||0;
						this.originalPrice=this.originalPrice+item.count*item.model.price*100
						if(typeof item.model.specificationsValue=="object"){
							item.model.specificationsValue=JSON.stringify(item.model.specificationsValue)
						}
						if(item.wares){
							item.name=item.wares.name
						}
					})
					this.originalPrice=this.originalPrice+this.freight*100
					this.totalPirce=this.originalPrice;
				}
				else  {
					this.orderList.forEach((item)=>{
						this.freight=this.freight+item.model.freight||0;
						this.originalPrice=this.originalPrice+item.count*item.model.price*100;
						item.name=item.wares.name;
					})
					this.originalPrice=this.originalPrice+this.freight*100
					this.totalPirce=this.originalPrice;
				}
				console.log(this.orderList)
			 this.showPage=true;
			 uni.hideLoading();
			 await this.getCouponData();
			},
		},
		onLoad(data) {
			console.log(data);
		     this.$bus.$on('chooseAddress', (obj)=>{
		     	 this.address=obj
				 this.addressList=[]
				 this.addressList.push(obj)
		     	 this.showDefault=false
		     });
		  if(typeof data !== 'object'){
			 data=JSON.parse(data)
		  }
		 
		  this.orderFrom=data.orderFrom
		  this.orderList=data.list
		  this.shareUserId=data.shareUserId
		  console.log(this.shareUserId)
		  if(typeof this.orderList !== 'object'){
			 this.orderList=JSON.parse(this.orderList) 
		  }
		   console.log(this.orderList)
			this.init();
		},
		onShow() {
			if(this.showDefault){
				 this.showAddress=false;
				var obj={nowPage:1,pageSize:9999,startRecord:0,parameters:{},condition:{oredCriteria:[[]]}}
				api.SM_SHIPPING_ADDRESS_LIST_FOR_PAGE(JSON.stringify(obj)).then((res)=>{
					 this.addressList=res.data.body.exhibitDatas
					 this.address=this.addressList[0]
					 this.showAddress=true
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.redColor{
		color: red;
		font-weight: bold;
		font-size:60rpx;
	}
	.checkedbox{
		position: absolute;
		right: 10rpx;
		top: 10vh;
	}
	.van-ellipsis{
		margin-left: 30rpx;
	}
	.shop-coupon{
		display: flex;
		flex-direction: row;
	    align-items: center;
		margin: 30rpx 0rpx;
	}
	.shop-coupon--left{
		display: flex;
		flex-direction: column;
		justify-content: center;
		text-align: center;
		margin:0 30rpx;
		max-width: 30vw;
	}
	.coupon-item{
		background-color: #fff;
		width: 690rpx;
		margin: 30rpx;
		padding: 20rpx;
		padding-top: 1rpx;
		border-radius: 20rpx;
		font-weight: 600;
		font-size: 24rpx;
		position: relative;
	}
	.contain-empty{
		width: 100vw;
		height: 50vh;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
	.btn-div-v{
		width: 90vw;
		height: 80rpx;
		line-height: 80rpx;
		color: #fff;
		border-radius: 40rpx;
		text-align: center;
		margin-bottom: 30rpx;
	}
	.btn-fiexd-coupon{
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 100vw;
	}
	/deep/.van-field__control{
		font-weight: bold;
	}
	/deep/.van-field__word-limit{
		font-weight: bold;
	}
	/deep/.van-field__label{
		color: black;
		font-weight: bold;
	}
	.van-cell-text{
		   font-size: 3.8vw;
		    color: rgb(153, 153, 153);
		    margin-left: 4vw;
			font-weight: bold;
	}
	.van-cell-title{
		   color: black;
		    font-size: 3.8vw;
		   font-weight: bold;
	}
	.cell-left{
		display: flex;
		flex-direction: row;
	}
	/deep/.value-class{
		font-weight: bold;
		color: black;
	}
	 .pay-othermsg {
		width: 90vw;
		margin: 0 5vw;
	    color: #333;
	  }
	 .pay-shopping {
		 width: 90vw;
		 margin: 0 5vw;
	    margin-top: 3vw;
		margin-bottom: 3vw;
	    background: #fff;
	    padding: 4vw 4vw 7vw 4vw;
	    border-radius: 3vw;
	    box-shadow: 1px 1px 24px 0px rgba(79, 93, 117, 0.08);
	    color: #343434;
	    .shopping-title {
	      font-size: 4.2vw;
	      font-weight: bold;
	      display: flex;
	      image {
	        width: 5vw;
	        height: 5vw;
	        margin-right: 2vw;
	      }
	    }
	  }
	  .discount-cost {
	    font-size: 4vw;
	    line-height: 5vw;
	    color: #333;
	    display: flex;
	    margin-top: 3vw;
	    justify-content: space-between;
	    view:last-child {
	      font-size: 4.5vw;
	      color: #cc363c;
	    }
	  }
	  .shopping-shop {
	    margin-top: 8vw;
	    display: flex;
	    .shopping-shop--img {
	      height: 30vw;
	      width: 30vw;
	      .van-image {
	        border-radius: 3vw;
	      }
	    }
	    .shopping-shop--text {
		  font-weight: bold;
	      width: 52vw;
	      & > view:first-child {
	        font-size: 4vw;
	      }
	      & > view:nth-child(2) {
	        font-size: 3.9vw;
	        color: #9a9a9a;
	        margin: 5vw 0 5vw 0;
	      }
	      & > view:nth-child(3) {
	        display: flex;
	        justify-content: space-between;
	        view:first-child {
	          color: #cc363c;
	          font-size: 5vw;
	        }
	        view:last-child {
	          font-size: 4.8vw;
	        }
	      }
	    }
	  }
	.pay-address {
		width: 90vw;
		margin: 0 5vw;
	    background: #fff;
	    margin-top: 4vw;
	    box-shadow: 1px 1px 24px 0px rgba(79, 93, 117, 0.08);
	    border-radius: 3vw;
	    padding: 4vw 4vw 7vw 4vw;
	    .address-userinfo {
	      display: flex;
	      align-items: flex-end;
	      view {
	        margin-right: 2.5vw;
	      }
	      .address-userinfo--icon {
	        width: 5vw;
	        height: 5vw;
	        margin-bottom: 1.6px;
			margin-right: 10rpx;
	      }
	      .address-userinfo--name {
	        color: #343434;
	        font-size: 4.5vw;
	        font-weight: bold;
	      }
	      .address-userinfo--tel {
	        color: #9a9a9a;
	        font-size: 3.6vw;
	        font-weight: bold;
	      }
	    }
	    .address-detail {
	      color: #343434;
	      font-size: 4.2vw;
	      font-weight: 600;
	      margin-top: 4vw;
	      display: flex;
	      justify-content: space-between;
	      align-items: center;
	      margin-left: 7.5vw;
	      line-height: 7vw;
	      view:last-child {
	        color: #c8c8cc;
	      }
	    }
	  }
	  .pay-address:active {
	    background: #f2f3f5;
	  }
     .contain {
     	width: 100vw;
     	min-height: 100vh;
     	display: flex;
     	flex-direction: column;
     	align-items: center;
     	background: rgb(245,247,249);
		padding-bottom: 200rpx;
		margin-bottom: 1rpx;
     }
</style>
